package com.sunwayworld.dev.core.generate;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


import com.sunwayworld.dev.core.valueobject.JavaObject;
import com.sunwayworld.dev.io.freemarker.GenerateUtils;

public class GenerateHibernateXML {
	private JavaObject javaObject;

	private String srcPath;

	private String vmPath;

	private Map context = new HashMap();

	public GenerateHibernateXML(JavaObject javaObject) {

		this.javaObject = javaObject;
		
		this.vmPath = javaObject.getVmPath();
		this.context = javaObject.getContext();
		init();
	}
	
	public void init(){
		String srcPath=javaObject.getSrcPath();
		
		this.srcPath=srcPath.replaceAll(".java$",".hbm.xml");
		
	}

	public void generateCode() {
		try {

			GenerateUtils gf=new GenerateUtils();
			
			copyProperties(javaObject, context);
			gf.generate(vmPath,srcPath,context);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	private void copyProperties(Object provide, Map context) {

		if (provide == null || context == null)
			return;
		Field[] fields = provide.getClass().getFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			try {
				Object temp = fields[i].get(provide);
				if (temp != null) {
					context.put(fieldName, temp);
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
}
